<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
export default {
  name: "App",
  created() {
    // this.initWebSocket();
    // console.group("%c%s", "color:red", "created--实例创建完成状态");
    // console.log("---:",this.$store.state)
  },
  mounted() {},
  methods: {
    initWebSocket() {
      //初始化weosocket
      let token = this.getUuid()
      console.log("token:",token)
      localStorage.setItem("token",token)
      const wsuri = `ws://localhost:888/api/bluebox/${token}`; //这个地址由后端童鞋提供
      
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
      websocketonerror() {
      //连接建立失败重连
      console.log("error");
      this.initWebSocket();
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      // this.websocketsend(this.user)
      console.log("open!");
    },
  
    websocketonmessage(e) {
      let _this = this; //数据接收
      if (e.data == "连接成功") {
        //这个判断是我业务需求才加的
        return;
      }
      console.log("e=>", e)
      //业务需求，将socket接收到的值存进vuex
      _this.$store.state.bluebox.blueboxes = JSON.parse(e.data)
       //重新给store中的scorketId赋值（数据格式问题先转了json）
      console.log("blueboxes:",_this.$store.state.bluebox.blueboxes)
    },
    websocketsend(Data) {
      //数据发送
      console.log("data=>", Data);
      this.websock.send(Data);
    },
    websocketclose(e) {
      //关闭
      console.log("断开连接", e);
    },
     getUuid() {
      var len = 16; //16长度
      var radix = 16; //16进制
      var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
        ""
      );
      var uuid = [],
        i;
      radix = radix || chars.length;
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
      } else {
        var r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
        uuid[14] = "4";
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | (Math.random() * 16);
            uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join("");
    }
  }
};
</script>
